package com.gqj.meter.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.BusinessConstants;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.DateUtils;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.meter.domain.*;
import com.gqj.meter.mapper.MdConcentratorMapper;
import com.gqj.meter.mapper.MdItMapper;
import com.gqj.meter.mapper.MdMeterMapper;
import com.gqj.meter.mapper.MdOutTaskDetailsMapper;
import com.gqj.meter.service.IMdOutTaskService;
import com.gqj.soapclient.client;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 出入库任务Controller
 *
 * @author lxq
 * @date lxq-02-10
 */
@Api(value = "/meter/mdOutTask", description = "出库任务")
@RestController
@RequestMapping("/meter/mdOutTask")
public class MdOutTaskController extends BaseController {
    @Autowired
    private IMdOutTaskService mdOutTaskService;
    @Autowired
    private MdOutTaskDetailsMapper mdOutTaskDetailsMapper;
    @Value("${downloadPath}")
    private String downloadPath;
    @Autowired
    private MdMeterMapper mdMeterMapper;
    @Autowired
    private MdConcentratorMapper mdConcentratorMapper;
    @Autowired
    private MdItMapper mdItMapper;

    /**
     * 查询出入库任务列表
     */
    @ApiOperation("查询出库任务列表")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTask:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdOutTask mdOutTask) {
        startPage();
        List<MdOutTask> list = mdOutTaskService.selectMdOutTaskList(mdOutTask);
        return getDataTable(list);
    }

    /**
     * 导出出入库任务列表
     */
    @PreAuthorize("@ss.hasPermi('meter:mdOutTask:export')")
    @Log(title = "出库任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdOutTask mdOutTask) {
        List<MdOutTask> list = mdOutTaskService.selectMdOutTaskList(mdOutTask);
        ExcelUtil<MdOutTask> util = new ExcelUtil<MdOutTask>(MdOutTask.class);
        util.exportExcel(response, list, "出入库任务数据");
    }

    /**
     * 获取出入库任务详细信息
     */
    @ApiOperation("获取出库任务详细信息")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTask:query')")
    @GetMapping(value = "/{outTaskId}")
    public AjaxResult getInfo(@PathVariable("outTaskId") Long outTaskId) {
        return success(mdOutTaskService.selectMdOutTaskByOutTaskId(outTaskId));
    }

    /**
     * 新增出库任务
     */
    @ApiOperation("新增出库任务")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTask:add')")
    @Log(title = "出库任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MdOutTask mdOutTask) {
        mdOutTask.setOperationUserId(getUserId());
        return toAjax(mdOutTaskService.insertMdOutTask(mdOutTask));
    }

    /**
     * 修改出入库任务
     */
    @ApiOperation("修改出库任务")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTask:edit')")
    @Log(title = "出库任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdOutTask mdOutTask) {
        if (UserConstants.NOT_UNIQUE.equals(mdOutTaskService.checkInTaskNoUnique(mdOutTask))) {
            return AjaxResult.error("修改'" + mdOutTask.getOutTaskNo() + "'任务失败，任务编号已存在");
        }
        MdOutTask mdOutTaskTemp = mdOutTaskService.selectMdOutTaskByOutTaskId(mdOutTask.getOutTaskId());
        if (!"0".equals(mdOutTaskTemp.getStatusCode())) {
            return AjaxResult.error("修改'" + mdOutTask.getOutTaskNo() + "'任务失败，任务已执行不允许修改");
        }

        MdOutTaskDetails MdOutTaskDetailsQuery = new MdOutTaskDetails();
        MdOutTaskDetailsQuery.setOutTaskNo(mdOutTask.getOutTaskNo());
//        int num = mdOutTaskDetailsMapper.selectMdOutTaskDetailsCount(MdOutTaskDetailsQuery);
//        if (num > 0) {
//            boolean isUpdate = !Objects.equals(mdOutTask.getVoltCode(), mdOutTaskTemp.getVoltCode()) ||
//                    !Objects.equals(mdOutTask.getCurrentCode(), mdOutTaskTemp.getCurrentCode()) ||
//                    !Objects.equals(mdOutTask.getApPreLevelCode(), mdOutTaskTemp.getApPreLevelCode()) ||
//                    !Objects.equals(mdOutTask.getWiringMode(), mdOutTaskTemp.getWiringMode()) ||
//                    mdOutTask.getOutNumber() != mdOutTaskTemp.getOutNumber();
//            if (isUpdate) {
//                return AjaxResult.error("修改'" + mdOutTask.getOutTaskNo() + "'任务失败，任务已有明细不允许更改接线方式、数量等信息");
//            }
//        }
        return toAjax(mdOutTaskService.updateMdOutTask(mdOutTask));
    }

    /**
     * 删除出入库任务
     */
    @ApiOperation("删除出库任务")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTask:remove')")
    @Log(title = "出库任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{outTaskIds}")
    public AjaxResult remove(@PathVariable Long[] outTaskIds) {
        return toAjax(mdOutTaskService.deleteMdOutTaskByOutTaskIds(outTaskIds));
    }

    /**
     * 修改出库任务状态
     */
    @ApiOperation("修改出库任务状态")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTask:editStatus')")
    @Log(title = "出库任务", businessType = BusinessType.UPDATE)
    @PostMapping("/editStatus")
    public AjaxResult editStatus(@RequestBody MdOutTask mdOutTask) throws IOException, ParserConfigurationException, SAXException {
        Long outTaskId = mdOutTask.getOutTaskId();
        if (null == outTaskId) {
            return AjaxResult.error("任务主键为null，请联系系统管理员！");
        }

        String statusCode = mdOutTask.getStatusCode();
        if (null == statusCode || "".equals(statusCode)) {
            return AjaxResult.error("任务状态代码为null，请联系系统管理员！");
        }

        MdOutTask mdOutTaskTemp = mdOutTaskService.selectMdOutTaskByOutTaskId(outTaskId);

        if (statusCode.equals("2") && !mdOutTaskTemp.getStatusCode().equals("1")) {
            return AjaxResult.error("该任务不是执行中状态，无法完成！");
        }

        if (statusCode.equals("1") && !mdOutTaskTemp.getStatusCode().equals("0")) {
            return AjaxResult.error("该任务不是待执行状态，无法执行！");
        }

        mdOutTask.setAssetsCategory(mdOutTaskTemp.getAssetsCategory());
        mdOutTask.setOutTaskNo(mdOutTaskTemp.getOutTaskNo());

        if (statusCode.equals("2")) {

            mdOutTask.setOperationDate(DateUtils.getNowDate());
            //修改子表完成
            List<MdOutTaskDetails> mdOutTaskDetailsList = mdOutTaskDetailsMapper.selectMdOutTaskDetailsList(new MdOutTaskDetails() {{
                setOutTaskNo(mdOutTaskTemp.getOutTaskNo());
            }});
            for (MdOutTaskDetails mdOutTaskDetails : mdOutTaskDetailsList) {
                mdOutTaskDetails.setOperationDate(DateUtils.getNowDate());
                mdOutTaskDetails.setIsComplete(BusinessConstants.IS_COMPLETE);
                mdOutTaskDetailsMapper.updateMdOutTaskDetails(mdOutTaskDetails);

                if(mdOutTaskTemp.getAssetsCategory().equals(BusinessConstants.ASSETS_CATEGORY_METER)){
                    mdMeterMapper.updateMdMeter(new MdMeter(){{
                        setMeterId(mdOutTaskDetails.getAssetsId());
                        setServiceStatus(BusinessConstants.SERVICE_STATUS_OUT);
                    }});
                }else if(mdOutTaskTemp.getAssetsCategory().equals(BusinessConstants.ASSETS_CATEGORY_CONCENTRATOR)){
                    mdConcentratorMapper.updateMdConcentrator(new MdConcentrator(){{
                        setConcentratorId(mdOutTaskDetails.getAssetsId());
                        setServiceStatus(BusinessConstants.SERVICE_STATUS_OUT);
                    }});
                }else if(mdOutTaskTemp.getAssetsCategory().equals(BusinessConstants.ASSETS_CATEGORY_IT)){
                    mdItMapper.updateMdIt(new MdIt(){{
                        setItId(mdOutTaskDetails.getAssetsId());
                        setServiceStatus(BusinessConstants.SERVICE_STATUS_OUT);
                    }});
                }
            }
        }

        return toAjax(mdOutTaskService.updateMdOutTaskStatus(mdOutTask));
    }

    /**
     * 下载出库单json文件
     */
    @ApiOperation("下载出库json文件")
    @PreAuthorize("@ss.hasPermi('meter:mdOutTask:downloadJsonMdOutTask')")
    @GetMapping("/downloadJsonMdOutTask")
    public AjaxResult downloadJsonMdInTask(MdOutTask mdOutTask) {
        //只下载任务开始的单据
        mdOutTask.setStatusCode("1");
        Long[] outTaskIds = mdOutTask.getOutTaskIds();
        for (int i = 0; i < outTaskIds.length; i++) {
            MdOutTask outTask = mdOutTaskService.selectMdOutTaskByOutTaskId(outTaskIds[i]);
            if (!"1".equals(outTask.getStatusCode())) {
                return AjaxResult.error("单据" + outTask.getOutTaskNo() + "不是开始开始执行状态，请重新选择!");
            }
        }
        List<MdOutTask> pos = mdOutTaskService.selectMdOutTaskList(mdOutTask);

        String orderNo = StorageUtil.getOrderNoTo12();

        String fileName = downloadPath;
        String jsonStringAc = JSON.toJSONString(pos);
        StorageUtil.createJsonFile(jsonStringAc, fileName, "出库单数据" + orderNo);
        return AjaxResult.success(fileName + "出库单数据" + orderNo);
    }
}
